/**
 *
 */
package com.yinhai.activity;

import android.app.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lz.util.SystemParsUtils;
import com.yinhai.adapter.DialAdapter;
import com.yinhai.adapter.DialAllRecordAdapter;
import com.yinhai.adapter.DialInContactAdapter;
import com.yinhai.dao.PhoneRecordDaoImpl;
import com.yinhai.dialog.DialDialog;
import com.yinhai.model.ContactsUser;
import com.yinhai.model.PhoneRecord;
import com.yinhai.service.ContactUserServiceImpl;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Juyon
 */
public class DialFragment extends Fragment {


    private static View navRecWindow = null;

    private static TextView titleView = null;

    // 弹出记录列表
    private static ListView mLv_pop_rec = null;

    // 主界面
    private static View view_main = null;


    // 显示通话类型：未接电话，已接电话等等
    private PopupWindow mPdw_types = null;


    // 列表项记录弹出窗口
    private static PopupWindow mPdw_nav_record = null;

    List<PhoneRecord> tonghuajiList = new ArrayList<PhoneRecord>();

    DialAdapter adapter = null;

    // t通话记录
    private static ListView recordListView = null;

    private List<ContactsUser> contactsUserLst = new ArrayList<ContactsUser>();

    private DialInContactAdapter contactAdapter;

    private ListView contactListView;


    private PhoneRecordDaoImpl phoneRecordDaoImpl = null;

    private ContactUserServiceImpl contactUserServiceImpl = null;

    private FragmentActivity activity = null;

    // 列表项中的电话号码
    private static String itemTelphone = null;

    private static String itemTelphoneName = null;


    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        activity = this.getActivity();
        if (phoneRecordDaoImpl == null) {
            phoneRecordDaoImpl = new PhoneRecordDaoImpl(activity);
        }
        if (contactUserServiceImpl == null) {
            contactUserServiceImpl = new ContactUserServiceImpl(activity);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        try {

            view_main = inflater.inflate(R.layout.main_dial, null);

            try {
                titleView = (TextView) view_main.findViewById(R.id.titleView);
                titleView.setOnClickListener(onClickListener);

                recordListView = (ListView) view_main.findViewById(R.id.record_contact_list);
                adapter = new DialAdapter(activity, tonghuajiList);
                recordListView.setAdapter(adapter);
                recordListView.setOnItemClickListener(onItemClickListener);

                contactListView = (ListView) view_main.findViewById(R.id.dial_contact_list);
                contactAdapter = new DialInContactAdapter(getActivity(), contactsUserLst, "");
                contactListView.setAdapter(contactAdapter);
                contactListView.setOnItemClickListener(onItemClickListener);

                // new MyAsyncQueryHandler(activity).execute(0);


                // 初始化itemview弹出框

                // 初始化itemview中记录弹出框
                navRecWindow = inflater.inflate(R.layout.pop_dial_allrecord, null);

                // 点击头像弹出popupwindow
                // LayoutInflater inflater1 = LayoutInflater.from(activity);
                // View menu = inflater1.inflate(R.layout.dial_nav, null);
                // 新增或者查看详情按钮

                builder =
                        new AlertDialog.Builder(activity).setTitle("操作选择").setItems(types,
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        titleView.setText(types[which]);
                                        switch (which) {

                                            case 0:
                                                // 全部来电
                                                new MyAsyncRecordQueryHandler(activity).execute(0);

                                                break;
                                            case 1:
                                                // 已接
                                                new MyAsyncRecordQueryHandler(activity).execute(1);
                                                break;
                                            case 2:
                                                // 已拨
                                                new MyAsyncRecordQueryHandler(activity).execute(2);
                                                break;
                                            case 3:
                                                // 未接
                                                new MyAsyncRecordQueryHandler(activity).execute(3);
                                                break;
                                            case 4:
                                                // 拒接
                                                new MyAsyncRecordQueryHandler(activity).execute(4);
                                                break;

                                            default:
                                                break;
                                        }
                                    }
                                });

            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return view_main;
    }





    /**
     * 初始化拨号盘
     */
    public void dialInputText(CharSequence s) {

        if (getActivity() == null) {
            return;
        }
        if (s.length() > 0) {
            // Juyon
            char first = s.charAt(0);
//                    Log.i("xxx55", System.currentTimeMillis()+"");
//                    if(s.length() == 1) {
//                		contactsUserLst.clear();
//                        contactsUserLst.addAll(new ArrayList<ContactsUser>());
//                        contactAdapter.notifyDataSetChanged();
//                	}
//                    Log.i("xxx55", System.currentTimeMillis()+"");
//                    Log.i("xxx55", System.currentTimeMillis()+"x1");
            if ('1' == first) {
                if (s.length() > 2) {
                    new MyAsyncContactQueryHandler(activity).execute(10);
                    recordListView.setVisibility(View.GONE);
                    contactListView.setVisibility(View.VISIBLE);
                }
            } else {
                new MyAsyncContactQueryHandler(activity).execute(10);
                recordListView.setVisibility(View.GONE);
                contactListView.setVisibility(View.VISIBLE);
            }
        } else if (s.length() == 0) {
            new MyAsyncRecordQueryHandler(activity).execute(0);
            recordListView.setVisibility(View.VISIBLE);
            contactListView.setVisibility(View.GONE);
        }



    }

    private OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
            try {
                if (recordListView.getVisibility() == View.VISIBLE) {
                    PhoneRecord record = (PhoneRecord) adapter.getItem(arg2);
                    itemTelphone = record.getTelPhone();
                    itemTelphoneName = record.getName();
                } else {
                    ContactsUser record = (ContactsUser) contactAdapter.getItem(arg2);
                    itemTelphone = record.getTelPhone();
                    itemTelphoneName = record.getName();
                }


                DialDialog d = new DialDialog(getActivity());
                d.itemTelphone = itemTelphone;
                d.show();


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    private static String[] types = new String[]{"通话记录", "已接电话", "已拨电话", "未接电话", "拒绝来电"};

    private AlertDialog.Builder builder = null;


    // 拨号
    public static void dial(Context activity, String telNo) {
        if (telNo != null && telNo.length() > 0) {
            Uri uri = Uri.parse("tel:" + telNo);
            Intent intent = new Intent(Intent.ACTION_CALL, uri);
            activity.startActivity(intent);
        }
    }

    // 发短信
    public static void msg(Context context, String telNo) {
        // if (telNo != null && telNo.length() > 0) {
        // Uri uri = Uri.parse("smsto:" + telNo);
        // Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        // getActivity().startActivity(intent);
        // }
        try {

            // String threadId = ContactUserServiceImpl.phoneThreads.get(telNo);


        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri uri = Uri.parse("content://sms");
        String[] projection = new String[]{"thread_id", "address"}; //
        // 查询的列
        new MyAsynQueryHandler(context).startQuery(0, null, uri,
                projection, "( address =  +86" + telNo + "  or address =  " + telNo + ")", null, null);
    }

    // 通过电话号码异步查询thread_id
    private static class MyAsynQueryHandler extends AsyncQueryHandler {
        private Context contextt;

        public MyAsynQueryHandler(Context context) {
            super(context.getContentResolver());
            contextt = context;
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            try {

                super.onQueryComplete(token, cookie, cursor);
                if (cursor.getCount() > 0) {
                    cursor.moveToFirst();
                    long threadId = cursor.getLong(cursor.getColumnIndex("thread_id"));
                    cursor.close();
                    //String address = cursor.getString(cursor.getColumnIndex("address"));
                    Intent intent = new Intent(contextt, SMSDetailActivity.class);
                    intent.putExtra("threadId", String.valueOf(threadId));
                    intent.putExtra("address", itemTelphone);
                    intent.putExtra("displayName", itemTelphoneName);
                    contextt.startActivity(intent);
                } else {
                    Intent intent = new Intent(contextt, SMSDetailActivity.class);
                    intent.putExtra("threadId", "");
                    intent.putExtra("address", itemTelphone);
                    intent.putExtra("displayName", itemTelphoneName);
                    contextt.startActivity(intent);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    ;

    // 详情
    // private void detail(String telNo) {
    //
    // }

    private class MyAsyncRecordQueryHandler extends AsyncTask<Integer, Integer, List<PhoneRecord>> {

        private Context ctx;

        private int type = 1;// 1:通话记录 2：联系电话

        private String dialNum = "";

        public MyAsyncRecordQueryHandler(Context ctx) {
            this.ctx = ctx;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected List<PhoneRecord> doInBackground(Integer... params) {
            try {

                return phoneRecordDaoImpl.find(params[0], "");

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<PhoneRecord> result) {
            super.onPostExecute(result);
            if (result != null) {
                if (type == 1) {
                    tonghuajiList.clear();
                    tonghuajiList.addAll(result);
                    adapter.notifyDataSetChanged();
                }
            }

        }

    }

    private class MyAsyncContactQueryHandler extends AsyncTask<Integer, Integer, List<ContactsUser>> {

        private Context ctx;

        private String dialNum = "";

        public MyAsyncContactQueryHandler(Context ctx) {
            this.ctx = ctx;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected List<ContactsUser> doInBackground(Integer... params) {
//        	 Log.i("xxx55", System.currentTimeMillis()+"x3");
            try {

                MainActivity activity = (MainActivity) getActivity();

                String str = activity.inputNum.getText().toString();
                dialNum = str;
//                Log.i("xxx55", System.currentTimeMillis()+"x4");
                List<ContactsUser> l = contactUserServiceImpl.findContact(str,
                        SystemParsUtils.getInstance(getActivity()).getInt("dialSearch", -1));
//                Log.i("xxx55", System.currentTimeMillis()+"x5");
                return l;

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<ContactsUser> result) {
            Log.i("xxx55", System.currentTimeMillis() + "x6");
            super.onPostExecute(result);
            Log.i("xxx55", System.currentTimeMillis() + "x7");
            if (result != null) {
                Log.i("xxx55", System.currentTimeMillis() + "x8");
                contactsUserLst.clear();
                contactsUserLst.addAll(result);
                contactAdapter.setDialNum(dialNum);
                contactAdapter.notifyDataSetChanged();
                Log.i("xxx55", System.currentTimeMillis() + "x9");
            }

        }

    }

    private class RecAsyncQueryHandler extends AsyncTask<Integer, Integer, BaseAdapter> {

        private Context ctx;

        public RecAsyncQueryHandler(Context ctx) {
            this.ctx = ctx;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected BaseAdapter doInBackground(Integer... params) {
            try {

                return new DialAllRecordAdapter(ctx, phoneRecordDaoImpl.find(params[0], itemTelphone));

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(BaseAdapter result) {
            super.onPostExecute(result);
            if (result != null) {
                mLv_pop_rec.setAdapter(result);
                mPdw_nav_record.showAtLocation(getView(), Gravity.CENTER, 0, 0);
            }

        }

    }

    @Override
    public void onResume() {

        super.onResume();
        try {
            new MyAsyncRecordQueryHandler(getActivity()).execute(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // if (mPdw_nums != null && mPdw_nums.isShowing()) {
        // mPdw_nums.dismiss();
        // }
        if (mPdw_types != null && mPdw_types.isShowing()) {
            mPdw_types.dismiss();
        }

        if (mPdw_nav_record != null && mPdw_nav_record.isShowing()) {
            mPdw_nav_record.dismiss();
        }
    }

    // 标题按钮点击事件
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dial_nav_call:
                    // 拨号导航
                    dial(getActivity(), itemTelphone);
                    break;


                default:
                    break;
            }
        }
    };


}